from flask import Blueprint, render_template, current_app, send_from_directory, redirect, url_for, request
from app import cache
import socket
import os
import datetime
import json

main_bp = Blueprint('main', __name__)

def get_network_info():
    """获取网络信息（模拟数据）"""
    hostname = socket.gethostname()
    try:
        ip_address = socket.gethostbyname(hostname)
    except:
        ip_address = "127.0.0.1"
    
    return {
        'ip_address': ip_address,
        'hostname': hostname,
        'mac_address': "00:00:00:00:00:00",
        'interface': "eth0",
        'created_at': datetime.datetime.now().isoformat()
    }

def get_storage_stats():
    """获取存储统计信息（模拟数据）"""
    upload_dir = current_app.config['UPLOAD_FOLDER']
    total_size = 0
    file_count = 0
    
    if os.path.exists(upload_dir):
        for root, dirs, files in os.walk(upload_dir):
            file_count += len(files)
            for file in files:
                file_path = os.path.join(root, file)
                if os.path.isfile(file_path):
                    total_size += os.path.getsize(file_path)
    
    return {
        'recordings_count': file_count,
        'total_storage': total_size,
        'total_storage_readable': format_size(total_size),
        'last_recording_at': datetime.datetime.now().isoformat() if file_count > 0 else None,
        'updated_at': datetime.datetime.now().isoformat()
    }

def format_size(size):
    """格式化文件大小"""
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if size < 1024 or unit == 'TB':
            return f"{size:.2f} {unit}"
        size /= 1024

def detect_language():
    """检测用户首选语言"""
    # 获取Accept-Language头
    accept_language = request.headers.get('Accept-Language', '')
    
    # 默认语言为中文
    default_lang = 'zh'
    
    # 如果Accept-Language头存在
    if accept_language:
        # 简单解析Accept-Language头
        languages = accept_language.split(',')
        for lang in languages:
            # 提取语言代码
            lang_code = lang.split(';')[0].strip().lower()
            # 检查是否为中文
            if lang_code.startswith('zh'):
                return 'zh'
            # 检查是否为英文
            elif lang_code.startswith('en'):
                return 'en'
    
    # 如果没有找到匹配的语言，返回默认语言
    return default_lang

@main_bp.route('/')
def index():
    # 获取Prolific相关参数
    prolific_pid = request.args.get('PROLIFIC_PID', '')
    prolific_study_id = request.args.get('STUDY_ID', '')
    prolific_session_id = request.args.get('SESSION_ID', '')
    
    # 生成版本戳，用于突破缓存
    version_timestamp = int(datetime.datetime.now().timestamp())
    
    # 获取已完成数据
    completions_data = {}
    try:
        completions_file = os.path.join('logs/completions', 'completions.json')
        if os.path.exists(completions_file):
            with open(completions_file, 'r') as f:
                completions_data = json.load(f)
    except Exception as e:
        current_app.logger.error(f'读取完成数据出错: {str(e)}')
    
    # 获取默认语言
    default_lang = current_app.config.get('DEFAULT_LANGUAGE', 'zh')
    
    # 检查用户是否已完成
    already_completed = False
    completion_message = ''
    if prolific_pid and prolific_pid in completions_data:
        already_completed = True
        completion_message = current_app.config.get('COMPLETION_MESSAGE', '您已完成录音任务，感谢您的参与!')
    
    return render_template(
        'index.html',
        prolific_pid=prolific_pid,
        prolific_study_id=prolific_study_id,
        prolific_session_id=prolific_session_id,
        repetitions=current_app.config.get('REPETITIONS', 3),
        command_words=current_app.config.get('COMMAND_WORDS', []),
        speeds=current_app.config.get('SPEEDS', ['normal']),
        already_completed=already_completed,
        completion_message=completion_message,
        platform=current_app.config.get('PLATFORM', 'web'),
        lang=default_lang,
        version=version_timestamp  # 添加版本戳作为模板变量
    )

@main_bp.route('/prolific')
def prolific_index():
    """专用于Prolific平台的路由"""
    # 获取Prolific相关参数
    prolific_pid = request.args.get('PROLIFIC_PID', '')
    prolific_study_id = request.args.get('STUDY_ID', '')
    prolific_session_id = request.args.get('SESSION_ID', '')
    
    # 记录Prolific访问日志
    current_app.logger.info(f"Prolific访问: PID={prolific_pid}, STUDY_ID={prolific_study_id}, SESSION_ID={prolific_session_id}")
    
    # 生成版本戳，用于突破缓存
    version_timestamp = int(datetime.datetime.now().timestamp())
    
    # 获取已完成数据
    completions_data = {}
    try:
        completions_file = os.path.join('logs/completions', 'completions.json')
        if os.path.exists(completions_file):
            with open(completions_file, 'r') as f:
                completions_data = json.load(f)
    except Exception as e:
        current_app.logger.error(f'读取完成数据出错: {str(e)}')
    
    # 获取默认语言
    default_lang = current_app.config.get('DEFAULT_LANGUAGE', 'zh')
    
    # 检查用户是否已完成
    already_completed = False
    completion_message = ''
    completion_code = 'C15MASW8'  # 指定Prolific完成代码
    completion_url = f'https://app.prolific.com/submissions/complete?cc={completion_code}'
    
    if prolific_pid and prolific_pid in completions_data:
        already_completed = True
        completion_message = current_app.config.get('COMPLETION_MESSAGE', '您已完成录音任务，感谢您的参与!')
    
    return render_template(
        'index.html',
        prolific_pid=prolific_pid,
        prolific_study_id=prolific_study_id,
        prolific_session_id=prolific_session_id,
        repetitions=current_app.config.get('REPETITIONS', 3),
        command_words=current_app.config.get('COMMAND_WORDS', []),
        speeds=current_app.config.get('SPEEDS', ['normal']),
        already_completed=already_completed,
        completion_message=completion_message,
        platform='prolific',  # 明确指定平台为prolific
        completion_code=completion_code,  # 添加完成代码
        completion_url=completion_url,    # 添加完成URL
        lang=default_lang,
        version=version_timestamp
    )

@main_bp.route('/favicon.ico')
def favicon():
    """提供网站图标"""
    return send_from_directory(current_app.static_folder, 'favicon.ico')

@main_bp.route('/dashboard')
@cache.cached(timeout=60)
def dashboard():
    """渲染管理仪表板"""
    # 获取存储统计信息
    storage_stats = get_storage_stats()
    
    return render_template('dashboard.html',
                          storage_stats=storage_stats)

@main_bp.route('/recordings')
def recordings_page():
    """渲染录音列表页面"""
    return render_template('recordings.html')

@main_bp.route('/uploads/<path:filename>')
def uploaded_file(filename):
    """提供上传的文件"""
    return send_from_directory(current_app.config['UPLOAD_FOLDER'], filename) 